package com.gp;

import java.util.Collections;
import java.util.List;

import com.utils.Random;

// the selection implementation
public class Selection {
	
	// chromes list
	public List<Chrome> chromes = null;
	
	// chromes fitness sum
	public int sum = 0;
	
	// c'tor
	public Selection(List<Chrome> chromes) {
		this.chromes = chromes;
		updateFit();
	}
	
	// return the best chrome
	public Chrome getBestChrome() {
		return chromes.get(0);
	}
	
    // sort the chromes and update the fitness
    private void updateFit() {
    	Collections.sort(chromes);
    	int rank = chromes.size();
    	sum =0;
    	for (Chrome c : chromes){
    		c.setUpdatedFit(rank);
    		sum+=rank;
    		rank-=1;
    	}
    }
    
    // return random chrome
    public Chrome getRandomChrome() {
    	return chromes.get(Random.nextInt(chromes.size()));
    }
    
    // select chrome
	public Chrome rolleteSelection() {
		int rand = Random.nextInt(sum);
		
		int currentVal = 0;
		int currentChrome = 0;
		while (currentVal <= rand && currentChrome < chromes.size()) {
			currentVal += chromes.get(currentChrome).getUpdatedFit();
			currentChrome++;
		}
		
		return chromes.get(currentChrome-1);
	}
}
